package cn.miketsu.downloader;

import cn.miketsu.util.ConfigUtils;
import cn.miketsu.util.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.nio.charset.StandardCharsets;

/**
 * @author 王泽风
 * @date 2021/11/13
 */
public class CGDownloader {
    public static void download() throws Exception {
        String html = HttpUtils.doGet("https://yys.163.com/media/picture.html");
        if (StringUtils.isBlank(html)) {
            throw new Exception("未获取到网页内容！");
        }
        System.out.println("获取网页内容成功！");
        Document document = Jsoup.parse(html);
        Elements pics = document.getElementsByClass("target");

        String resolvingPower = ConfigUtils.getPropertiesIgnoreBlank("resolvingPower");

        pics.parallelStream()
                .filter(pic -> StringUtils.isNotBlank(pic.attr("href")) && pic.attr("href").contains(resolvingPower))
                .forEach(pic -> {
                    try {
                        String href = pic.attr("href");
                        String fileName = DigestUtils.md5Hex(href.getBytes(StandardCharsets.UTF_8)) + ".jpg";
                        HttpUtils.doGetDownload(href, fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
    }
}
